// pages/withdrawal/withdrawal.js
var common = require("../../utils/Conmon.js");
var districtId = 0;  //区或县ID
var district = '';   //区或县昵称
var citys = [];    //本地保存市对象数组
var districts = []; //本地保存区对象数组
var appData = getApp().globalData;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    titleName: '添加账户',
    bankId: 0,
    Type: 0,
    Soure: 0,
    Index: null,
    selected: true,
    selected1: false,
    BankNames: ['工商银行', '华夏银行', '农业银行', '邮政储蓄'],          //开户银行
    BranchNames: ['工行分支行', '建行分支行', '农行分支行', '中国银行分支行'],    //开户支行
    newProvinceId: 0,   //省ID所在下标
    newCityId: 0,       //市ID所在下标
    newDistrictId: 0,   //区ID所在下标
    textAddress: '',
    showProvinces: [],
    showCitys: [],
    showDistricts: [],
    Name: '',
    Phone: '',
    BankNo: '',
    Address: '',
    AliName: '',
    AliAccount: ''
  },
  /**
   * 绑定开户银行选择事件
   */
  bindBankNameChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index1: e.detail.value
    })
  },

  /**
   * 绑定支行选择事件
   */
  bindBranchNameChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index2: e.detail.value
    })
  },
  /**
    * 绑定区域设置表数据
    */
  bindAreaData: function (pID, cID, dID) {
    //获取省
    var that = this;
    var Plst = that.data.showProvinces;
    var Clst = that.data.showCitys;
    var Dlst = that.data.showDistricts;
    that.wxSubRequest('GET', appData.apiurl + 'member/api/Area/GetAreaByParentID', { parentID: 0 }, function (res) {
      if (res.code == 1200) {
        for (var i = 0; i < res.content.length; i++) {
          Plst.push(res.content[i])
        }
      }
      //重新赋值
      that.setData({
        showProvinces: Plst
      })
    })
    //获取市
    that.wxSubRequest('GET', appData.apiurl + 'member/api/Area/GetAreaByLevel', { level: 2 },
      function (res) {
        if (res.code == 1200) {
          for (var i = 0; i < res.content.length; i++) {
            if (res.content[i].ParentID == Plst[that.data.newProvinceId].ID)
              Clst.push(res.content[i])

            citys.push(res.content[i]); //绑定全部市
          }
        }
        //重新赋值
        that.setData({
          showCitys: Clst
        })
      })

    //获取区或县
    that.wxSubRequest('GET', appData.apiurl + 'member/api/Area/GetAreaByLevel', { level: 3 },
      function (res) {
        if (res.code == 1200) {
          for (var i = 0; i < res.content.length; i++) {
            if (res.content[i].ParentID == Clst[that.data.newCityId].ID)
              Dlst.push(res.content[i])

            districts.push(res.content[i]);  //绑定全部区或县
          }
        }
        //重新赋值
        that.setData({
          showDistricts: Dlst
        })
      })
  },

  /**
   * 省市区选择器
   */
  bindMultiPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    var that = this;
    var province = that.data.showProvinces[e.detail.value[0]].AreaName;
    var city = that.data.showCitys[e.detail.value[1]].AreaName;
    districtId = that.data.showDistricts[e.detail.value[2]].ID;
    district = that.data.showDistricts[e.detail.value[2]].AreaName;
    //重新赋值
    that.setData({
      newProvinceId: e.detail.value[0],
      newCityId: e.detail.value[1],      //市ID
      newDistrictId: e.detail.value[2],
      textAddress: province + ' ' + city + ' ' + district
    })

  },

  bindMultiPickerColumnChange: function (e) {
    console.log('修改的列为', e.detail.column, '，值为', e.detail.value);
    var that = this;
    var valId;
    var Dlen = [];
    switch (e.detail.column) {
      case 0:
        valId = that.data.showProvinces[e.detail.value].ID;
        var Clen = [];
        for (var i = 0; i < citys.length; i++) {
          if (citys[i].ParentID == valId) {
            Clen.push(citys[i])
          }
        }
        for (var j = 0; j < districts.length; j++) {
          if (districts[j].ParentID == Clen[0].ID) {
            Dlen.push(districts[j])
          }
        }
        that.setData({
          showCitys: Clen,
          showDistricts: Dlen
        })
        break;
      case 1:
        valId = that.data.showCitys[e.detail.value].ID;
        for (var k = 0; k < districts.length; k++) {
          if (districts[k].ParentID == valId) {
            Dlen.push(districts[k])
          }
        }
        that.setData({
          showDistricts: Dlen
        })
        break;
    }
  },


  /**
  * 输入开户人姓名
  */
  bindNameInTap: function (e) {
    this.setData({
      Name: e.detail.value
    })
  },

  /**
     * 输入联系电话
     */
  bindPhoneInTap: function (e) {
    this.setData({
      Phone: e.detail.value
    })
  },

  /**
    * 输入银行卡号
    */
  bindBankNoInTap: function (e) {
    this.setData({
      BankNo: e.detail.value
    })
  },
  /**
   * 输入详细地址
   */
  bindAddressInTap: function (e) {
    this.setData({
      Address: e.detail.value
    })
  },

  /**
     * 输入支付宝名称
     */
  bindZhiFuBaoNameInTap: function (e) {
    this.setData({
      AliName: e.detail.value
    })
  },
  /**
    * 输入支付宝账户
    */
  bindZhiFuBaoCodeInTap: function (e) {
    this.setData({
      AliAccount: e.detail.value
    })
  },


  /**
   * 绑定点击保存事件
   */
  bindSaveClickTap: function () {
    var that = this;
    var indx = that.data.index1;
    var indx2 = that.data.index2;
    //保存的银行信息
    if (that.data.selected) {
      var pattern = /^1[34578]\d{9}$/;
      if (that.data.Name == '') {
        wx.showModal({ title: '警告', content: '请输入开户姓名', showCancel: false })
        return;
      }
      if (that.data.Phone == '') {
        wx.showModal({ title: '警告', content: '请输入联系电话', showCancel: false })
        return;
      }
      if (!pattern.test(that.data.Phone)) {
        wx.showModal({ title: '警告', content: '号码不对,请重新输入', showCancel: false })
        return;
      }
      if (that.data.BankNo == '') {
        wx.showModal({ title: '警告', content: '请输入银行账号', showCancel: false })
        return;
      }
      if (that.data.BankNames[indx] == '' || that.data.BankNames[indx] == undefined) {
        wx.showModal({ title: '警告', content: '请选择开户银行', showCancel: false })
        return;
      }
      if (districtId == '' || districtId == 0) {
        wx.showModal({ title: '警告', content: '请选择开户地区', showCancel: false })
        return;
      }
      if (that.data.BranchNames[indx2] == '' || that.data.BranchNames[indx2] == undefined) {
        wx.showModal({ title: '警告', content: '请选择开户支行', showCancel: false })
        return;
      }
      if (that.data.Address == '') {
        wx.showModal({ title: '警告', content: '请输入开户详细地址', showCancel: false })
        return;
      }
    } else {
      if (that.data.AliName == '') {
        wx.showModal({ title: '警告', content: '请输入账户名称', showCancel: false })
        return;
      }
      if (that.data.AliAccount == '') {
        wx.showModal({ title: '警告', content: '请输入支付宝账号', showCancel: false })
        return;
      }
    }

    var url = 'member/api/UserBankInfo/Add';
    var param = {};
    if (that.data.Index != null && that.data.Index > 0) {
      //银行卡
      param = { CustID: appData.custID, UserID: wx.getStorageSync('UserInfo').UserID, Name: that.data.Name, Phone: that.data.Phone, BankNo: that.data.BankNo, BankName: that.data.BankNames[indx], AreaID: districtId, BranchName: that.data.BranchNames[indx2], address: that.data.Address };
    } else {
      //支付宝
      param = { CustID: appData.custID, UserID: wx.getStorageSync('UserInfo').UserID, AliName: that.data.AliName, AliAccount: that.data.AliAccount };
    }
    if (that.data.bankId > 0) {
      param.ID = that.data.bankId;
      url = 'member/api/UserBankInfo/Update';
    }

    wx.showLoading({ title: '保存中...', mask: true });
    that.wxSubRequest('POST', appData.apiurl + url, JSON.stringify(param),
      function (res) {
        wx.hideLoading()
        if (res.code == 1200) {
          wx.showToast({
            title: '保存成功',
            duration: 2000,
            success: function () {
              wx.redirectTo({
                url: '/pages/bankCardList/bankCardList?type=' + that.data.Type + '&soure=' + that.data.Soure
              })
            }
          })
        } else {
          wx.hideLoading()
          wx.showModal({ title: '错误', content: '保存失败', showCancel: false })
        }
      },
      function (res) {
        wx.hideLoading()
        wx.showModal({ title: '错误', content: '保存失败,发生异常', showCancel: false })
      })
  },

  /**
   * 绑定加载数据
   */
  bindLoadData: function (_this) {
    wx.request({
      url: appData.apiurl + 'member/api/UserBankInfo/GetUserBank',
      method: 'GET',
      data: { "custId": appData.custID, "keyId": _this.data.bankId },
      header: {
        "content-type": "application/json",
        'X_ManuName': appData.manuName
      },
      success: function (res) {
        wx.hideLoading()
        if (res.statusCode == 200 && res.data.code == 1200) {
          var data = res.data.content;
          if (data != null) {
            //区域Id
            districtId = data.AreaID;
            if (districtId > 0) {
              _this.GetTextAddress(districtId, data)
            } else {
              _this.setData({
                AliName: data.AliName == null ? '' : data.AliName,
                AliAccount: data.AliAccount == null ? '' : data.AliAccount
              })
            }
          }
        }
      },
      fail: function (res) {
        wx.hideLoading()
        wx.showModal({ title: '错误', content: '请求获取异常错误', showCancel: false })
        console.log(res.data)
      }
    })
  },

  /**
   * 根据区域Id获取text
   */
  GetTextAddress: function (areaId, Obj) {
    var that = this;
    wx.request({
      url: appData.apiurl + 'member/api/UserBankInfo/GetCompleteAreaNameById',
      method: 'GET',
      data: { "areaId": areaId },
      header: {
        "content-type": "application/json",
        'X_ManuName': appData.manuName
      },
      success: function (res) {
        if (res.statusCode == 200 && res.data.code == 1200) {
          var textAddress = "";
          var _split = res.data.content.split(',');
          if (_split.length > 0) {
            for (var i = 0; i < _split.length; i++) {
              if (textAddress == "")
                textAddress = _split[i];
              else
                textAddress += " " + _split[i];
            }
          }
          var idex = -1;
          var idex2 = -1;
          for (var j = 0; j < that.data.BankNames.length; j++) {
            if (that.data.BankNames[j] == Obj.BankName) {
              idex = j;
              break;
            }
          }
          for (var k = 0; k < that.data.BranchNames.length; k++) {
            if (that.data.BranchNames[k] == Obj.BranchName) {
              idex2 = k;
              break;
            }
          }
          //绑定数据
          that.setData({
            Name: Obj.Name == null ? '' : Obj.Name,
            Phone: Obj.Phone == null ? '' : Obj.Phone,
            BankNo: Obj.BankNo == null ? '' : Obj.BankNo,
            index1: idex,
            textAddress: textAddress,
            index2: idex2,
            Address: Obj.address
          })

        }
      },
      fail: function (res) {
        wx.showModal({ title: '错误', content: '请求获取异常错误', showCancel: false })
        console.log(res.data)
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    common.pageInit( function () {
    });
    var that = this;
    var _type = options.type;
    var _soure = options.soure;
    var _bankId = options.bankId;
    var _index = options.Index;

    if (_bankId != null && _bankId != undefined) {
      if (Number(_bankId) > 0 && _bankId != '') {
        that.setData({
          titleName: '编辑账户',
          bankId: Number(_bankId)
        })
        wx.showLoading({ title: '加载中...', mask: true });
        that.bindLoadData(that);
      }
    }

    if (_index != null || _index != undefined) {
      if (_index == 0) {
        that.setData({
          selected: false,
          selected1: true,
          Soure: _soure,
          Type: _type,
          Index: _index
        })
      } else {
        that.setData({
          selected: true,
          selected1: false,
          Soure: _soure,
          Type: _type,
          Index: _index
        })
      }
    }
    wx.setNavigationBarTitle({ title: that.data.titleName });  //修改title
    that.bindAreaData(0, 0, 0);  //加载省市区数据绑定
  },


  /**
   * tab页切换
   */
  selected: function (e) {
    this.setData({
      selected: true,
      selected1: false
    })
  },
  /**
   * tab页切换
   */
  selected1: function (e) {
    this.setData({
      selected: false,
      selected1: true
    })
  },

  /**
   * 微信提交请求获取数据或保存数据
   * 
   */
  wxSubRequest: function (method, url, param, callBack, CallBackError) {
    wx.request({
      url: url,
      method: method,
      data: param,
      header: {
        "content-type": "application/json",
        'X_ManuName': appData.manuName
      },
      success: function (res) {
        if (res.statusCode == 200 && res.data.code == 1200) {
          var data = res.data;
          callBack(data)
          console.log(res.data)
        }
      },
      fail: function (res) {
        CallBackError(res.data)
        console.log(res.data)
      },
      complete: function (res) {
        console.log(res.msg)
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})